/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:event-recoder
 * Create Time: 2016年3月4日 上午8:34:40
 */
package com.lenovo.lmrp.server.eventrecorder.spi;

import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.lenovo.lmrp.base.GuiceRestServer;
import com.lenovo.lmrp.base.ParamNameDef;
import com.lenovo.sdc.framework.util.AttributeBean;

/**
 * 
 * @author wujin
 * @version v1.0
 */
public class EventRecorderRestServer {
    private static Logger logger = LoggerFactory.getLogger(EventRecorderRestServer.class);
    
    private GuiceRestServer restServer;
    private AttributeBean params;
    
    @Inject
    private Injector parentInjector;

    @Inject
    public EventRecorderRestServer(AttributeBean params) {
        this.params = params;
        restServer = new GuiceRestServer(
            params.getAttribute(ParamNameDef.REST_SERVER_HOST, "0.0.0.0"), 
            params.getAttribute(ParamNameDef.REST_SERVER_PORT, 7004), 
            params.getAttribute(ParamNameDef.REST_SERVER_SSL, false));
    }
    
    public void start() {
        // start REST API server, listening special port to receive income request
        restServer.start();
        logger.info("REST server has started, bind port {}", params.getAttribute(ParamNameDef.REST_SERVER_PORT, 7004));
        
        // indicate deployed rest api class location
        String[] scanpaths = new String[]{params.getAttribute(ParamNameDef.REST_API_SCANPATH, "com.lenovo.lmrp.server.eventrecorder.spi"),
                                          "com.lenovo.sdc.framework.rest"};
        
        // bind rest api class to child injector
        Injector child = null;
        if (Objects.isNull(parentInjector)) {
            parentInjector = Guice.createInjector(restServer.bind(scanpaths));
            child = parentInjector;
        }
        else
            child = parentInjector.createChildInjector(restServer.bind(scanpaths));
        
        // deploy REST service under GUICE env. to process request
        restServer.deploy(params.getAttribute(ParamNameDef.REST_SERVER_CONTEXT, ""), child.getBindings().values());
    }
    
    public void stop() {
        restServer.stop();
        logger.info("REST server try to shutdown...");
    }
}
